//
//  PictureCollectionVC.swift
//  PictureUpLoad
//
//  Created by mac on 16/4/22.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit

private let PictureCellId = "PictureCellId"

class PictureCollectionVC: UICollectionViewController {

    lazy var imageArray = [UIImage]()
    
    //记录当前被选中图片的索引
    var seletedIndex = 0
    
    //照片的最大数量
    var maxImageCount = 3
    
    init(){
        super.init(collectionViewLayout: pictureFlowLayout())
        
        //设置背景色
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PictureCellId)

    }


   //定义一个类种类，设置flow
    private class pictureFlowLayout: UICollectionViewFlowLayout{
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            let count:CGFloat = 4
            
            //设置具体的大小
            let margin = UIScreen.mainScreen().scale * 4
            
            let w = (UIScreen.mainScreen().bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSizeMake(w, w)
            
            minimumInteritemSpacing = margin
            
            minimumLineSpacing = margin
            
            sectionInset = UIEdgeInsetsMake(margin,margin,0,margin)
        }
        
    }

}

// MARK: UICollectionViewDataSource
extension PictureCollectionVC{
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       //如果没有达到最大值就加一，达到了就不加了
        return imageArray.count + (imageArray.count == maxImageCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PicturePickerCell
  
        
        cell.image = (indexPath.item<imageArray.count) ? imageArray[indexPath.row] : nil
        
        //设置代理
        cell.pictureDelegate = self
        
        return cell
    }
    
}

//控制器实现代理的方法
extension PictureCollectionVC: PicturePickerDelegate{
    
    @objc private func PicturePickerCellAdd(cell: PicturePickerCell) {
        
        //判断用户是否有权利访问用户的相册
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)
        {
            print("访问相册受限")
            return
        }
        
        seletedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        let picker = UIImagePickerController()
        
        //点击的时候弹出照片选择器的控制器
        presentViewController(picker, animated: true, completion: nil)
        //允许编辑，这种多用于可以自定义头部的图像，一个正方形的视图 UIImagePickerControllerEditedImage
//        picker.allowsEditing = true
        
        picker.delegate = self

    }
    
    @objc private func PicturePickerCellDel(cell: PicturePickerCell) {
        
        //获取到被点击的cell角标
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        //判断角标是否越界
        if indexPath.item >= imageArray.count{
            return
        }
        
        //删除选中的cell
        imageArray.removeAtIndex(indexPath.item)
        
        //刷新数据，进行显示
        collectionView?.reloadData()
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
    }
}

// picker 需要遵循两个协议方法
extension PictureCollectionVC:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // picker 照片选中器控制器， 这个方法一旦实现就需要自己dismiss
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //控制图片的大小
        let scaleImage = image.scaleToWidth(600)
//        imageArray.append(image)
        
       //判断所选中的图片是否越界
        if seletedIndex>=imageArray.count{//大于就插在后面
            imageArray.append(scaleImage)
        }else{//小于就插在当前
            imageArray[seletedIndex] = scaleImage
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
        
//        print(info)
    }
}


//设置两个点击的方法 ,代理的方法如果是可选项，就要在代理的方法申明前加一个@objc
@objc private protocol PicturePickerDelegate:NSObjectProtocol{
    
    optional func PicturePickerCellAdd(cell:PicturePickerCell)
    
    optional func PicturePickerCellDel(cell:PicturePickerCell)
}

private class PicturePickerCell:UICollectionViewCell{
    
    //设置代理属性
     weak var pictureDelegate: PicturePickerDelegate?
    
    var image: UIImage?{
        didSet{
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            
            //隐藏删除按钮
            delButton.hidden = (image == nil)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    private func setupUI(){
        
        //添加控件
        addSubview(addButton)
        addSubview(delButton)
        
        addButton.frame = bounds
        
        delButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
        }
        
        //注册监听方法
        addButton.addTarget(self, action: "addPictureClick", forControlEvents: .TouchUpInside)
        delButton.addTarget(self, action: "delPictureClick", forControlEvents: .TouchUpInside)
        
        //设置照片的填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    @objc private func addPictureClick(){
        
        pictureDelegate?.PicturePickerCellAdd?(self)
    }
    
    @objc private func delPictureClick(){
        //这里就相当于OC中的if判断，看代理是否实现。
        pictureDelegate?.PicturePickerCellDel?(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //懒加载控件
    private lazy var addButton:UIButton = UIButton(imageName: "compose_pic_add", backGroudImage: nil)
    private lazy var delButton:UIButton = UIButton(imageName: "compose_photo_close", backGroudImage: nil)

}












